package com.jgy.security.service;

import com.alibaba.fastjson.JSON;
import com.jgy.entity.Permission;
import com.jgy.mapper.SpaceUserMapper;
import com.jgy.security.model.AuthParamsDto;
import com.jgy.security.model.XcUserExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 姜光远
 * @date 2023/2/24 13:57
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private SpaceUserMapper mapper;
    @Autowired
    AuthService authService;
    @Autowired
    ApplicationContext applicationContext;

    /**
     * @description 查询用户信息组成用户身份信息
     * @param username  AuthParamsDto类型的json数据
     * @return org.springframework.security.core.userdetails.UserDetails
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AuthParamsDto authParamsDto = null;

        //将认证参数转为AuthParamsDto类型
        try {
            authParamsDto = JSON.parseObject(username, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}",username);
            throw new RuntimeException("认证请求数据格式不对");
        }
        //认证方法
        String authType = authParamsDto.getAuthType();
        AuthService authService =  applicationContext.getBean(authType + "_authservice",AuthService.class);
        XcUserExt execute = authService.execute(authParamsDto);

        return getUserPrincipal(execute);

    }

    /**
     * @description 查询用户信息
     * @param user  用户id，主键
     * @return com.xuecheng.ucenter.model.po.XcUser 用户信息
     */

    private UserDetails getUserPrincipal(XcUserExt user) {

        String id = user.getId();
        List<Permission> listRole = mapper.selectRole(id);
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities= {"p1"};
        String password = user.getPassword();
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(user);

        //创建UserDetails对象
        return User.withUsername(userString).password(password ).authorities(listRole).build();
    }
}
